#!/usr/bin/env python3
import sys
import os
import subprocess
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("❌ 错误: 需要Python 3.8或更高版本")
        print(f"当前版本: {sys.version}")
        sys.exit(1)
    print(f"✅ Python版本检查通过: {sys.version}")

def check_dependencies():
    """检查依赖包"""
    required_packages = [
        'playwright',
        'PyQt6',
        'pydantic',
        'loguru'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package.replace('-', '_').lower())
            print(f"✅ {package} 已安装")
        except ImportError:
            missing_packages.append(package)
            print(f"❌ {package} 未安装")
    
    if missing_packages:
        print(f"\n缺少以下依赖包: {', '.join(missing_packages)}")
        print("请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        print("playwright install")
        sys.exit(1)

def check_playwright_browsers():
    """检查Playwright浏览器"""
    try:
        from playwright.sync_api import sync_playwright
        with sync_playwright() as p:
            # 检查浏览器是否已安装
            chromium_path = p.chromium.executable_path
            if chromium_path and Path(chromium_path).exists():
                print("✅ Playwright浏览器已安装")
            else:
                print("❌ Playwright浏览器未安装")
                print("请运行: playwright install")
                sys.exit(1)
    except Exception as e:
        print(f"❌ Playwright检查失败: {e}")
        print("请运行: playwright install")
        sys.exit(1)

def setup_environment():
    """设置环境"""
    # 创建必要的目录
    directories = [
        'logs',
        'scripts/active',
        'scripts/archived', 
        'scripts/drafts'
    ]
    
    for directory in directories:
        Path(directory).mkdir(parents=True, exist_ok=True)
    
    # 检查.env文件
    if not Path('.env').exists():
        if Path('.env.example').exists():
            print("🔧 创建.env配置文件...")
            import shutil
            shutil.copy('.env.example', '.env')
            print("✅ .env文件已创建，您可以编辑它来自定义配置")
        else:
            print("⚠️  未找到.env.example文件")

def main():
    """主函数"""
    # 检查是否是CLI模式
    cli_mode = '--cli' in sys.argv
    
    if cli_mode:
        # CLI模式，跳过GUI相关检查
        print("🚀 UI自动化工具CLI模式启动...")
        print("=" * 50)
        
        check_python_version()
        check_dependencies()
        check_playwright_browsers()
        setup_environment()
        
        print("=" * 50)
        print("🎉 所有检查通过，正在启动CLI...")
        
        # 移除 --cli 参数并启动CLI
        sys.argv.remove('--cli')
        import asyncio
        try:
            from cli import main as cli_main
            asyncio.run(cli_main())
        except KeyboardInterrupt:
            print("\n👋 CLI已退出")
        except Exception as e:
            print(f"❌ CLI启动失败: {e}")
            sys.exit(1)
    else:
        # GUI模式
        print("🚀 UI自动化管理工具启动检查...")
        print("=" * 50)
        
        # 环境检查
        check_python_version()
        check_dependencies()
        check_playwright_browsers()
        setup_environment()
        
        print("=" * 50)
        print("🎉 所有检查通过，正在启动应用...")
        
        # 启动应用
        try:
            from main import main as app_main
            app_main()
        except KeyboardInterrupt:
            print("\n👋 应用已退出")
        except Exception as e:
            print(f"❌ 启动失败: {e}")
            sys.exit(1)

if __name__ == "__main__":
    main()